package com.yaorange.web.controller.certificate.wxapi;

import com.yaorange.common.config.RuoYiConfig;
import com.yaorange.common.core.domain.AjaxResult;
import com.yaorange.common.core.domain.entity.SysDictData;
import com.yaorange.common.utils.QiniuUtils;
import com.yaorange.common.utils.StringUtils;
import com.yaorange.system.service.ISysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Api(value = "通用接口", tags = "通用接口")
@RestController
@RequestMapping("/api/common")
public class CommonAPI {
    @Autowired
    private ISysDictTypeService dictTypeService;

    @Value("${ruoyi.uploadType}")
    private String uploadType;
    @Value("${ruoyi.serverUrl}")
    private String serverUrl;

    /**
     * 根据字典类型查询字典数据信息
     */
    @ApiOperation(value = "根据字典类型查询字典列表", notes = "根据字典类型查询字典列表")
    @ApiImplicitParam(name = "dictType", value = "字典类型", required = true, dataType = "String")
    @GetMapping(value = "/queryDictType")
    public AjaxResult queryDictType(@RequestParam("dictType") String dictType) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data)) {
            return AjaxResult.error("查询失败");
        }
        return AjaxResult.success(data);
    }

    @PostMapping(value = "/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file,@RequestParam("biz") String biz) {

        //1KL3JKJASKDFJASDJFKAS-jvm运行过程.png
        String originalFilename = UUID.randomUUID() + "-" + file.getOriginalFilename();
        try {
            if (uploadType.equals("local")) {
                String uploadPath = RuoYiConfig.getUploadPath();
                //D:/ruoyi/uploadPath/wechat/
                File saveDic = new File(uploadPath + "/" + biz);
                //判断目录是否存在
                if (!saveDic.exists()) {
                    saveDic.mkdirs();
                }

                file.transferTo(new File(saveDic, originalFilename));
                return AjaxResult.success(serverUrl + "/upload/" + biz + "/" + originalFilename);
            } else {
                //七牛云上传
                return AjaxResult.success(QiniuUtils.upload(file,originalFilename));
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
